<template>
  <div class="edit-popup">
    <popup
      ref="popupRef"
      :title="popupTitle"
      :async="true"
      width="650px"
      :clickModalClose="true"
      @confirm="handleSubmit"
      @close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        label-width="84px"
        :rules="formRules"
      >
        <div class="bor">
          <!-- 账号输入框 -->
          <el-form-item label="账号" prop="account">
            <el-input
              v-model="formData.account"
              :disabled="formData.root == 1"
              placeholder="请输入账号"
            >
            </el-input>
          </el-form-item>
          <!-- 管理员头像 -->
          <el-form-item label="头像">
            <div>
              <div>
                <pickerold v-model="formData.avatar" :limit="1" />
              </div>
              <div class="form-tips">
                建议尺寸：100*100px，支持jpg，jpeg，png格式
              </div>
            </div>
          </el-form-item>

          <!-- 名称输入框 -->
          <el-form-item label="名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入名称" />
          </el-form-item>
          <!-- <el-form-item label="归属部门" prop="dept_id">
					<el-tree-select class="flex-1" v-model="formData.dept_id" :data="options.dept" clearable
						node-key="id" :props="{
                            value: 'id',
                            label: 'name',
                            disabled(data: any) {
                                return data.status !== 1
                            }
                        }" check-strictly :default-expand-all="true" placeholder="请选择上级部门" />
				</el-form-item>
				<el-form-item label="归属部门" prop="dept_id">
					<el-select class="flex-1" v-model="formData.jobs_id" placeholder="请选择岗位">
						<el-option v-for="(item, index) in options.jobs" :key="index" :label="item.name"
							:value="item.id"></el-option>
					</el-select>
				</el-form-item> -->
          <!-- <el-form-item label="绑定仓库" prop="bind_warehouse_id">
					<el-select class="flex-1" v-model="formData.bind_warehouse_id" multiple placeholder="请选择岗位">
						<el-option v-for="(item, index) in options.listColumn" :key="index" :label="item.title"
							:value="item.id"></el-option>
					</el-select>
				</el-form-item> -->

          <!-- 角色选择框 -->
          <el-form-item label="角色" prop="role_id">
            <el-select
              v-model="formData.role_id"
              :disabled="formData.root == 1"
              class="flex-1"
              placeholder="请选择角色"
            >
              <el-option
                v-if="formData.root == 1"
                label="系统管理员"
                :value="0"
              ></el-option>
              <el-option
                v-for="(item, index) in options.role"
                :key="index"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <!-- 密码输入框 -->
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="formData.password"
              show-password
              placeholder="请输入密码"
            ></el-input>
          </el-form-item>

          <!-- 确认密码输入框 -->
          <el-form-item label="确认密码" prop="password_confirm">
            <el-input
              v-model="formData.password_confirm"
              show-password
              placeholder="请输入确认密码"
            ></el-input>
          </el-form-item>

          <!-- 管理员状态 -->
          <el-form-item label="管理员状态" v-if="formData.root != 1">
            <el-switch
              v-model="formData.disable"
              :active-value="0"
              :inactive-value="1"
            />
          </el-form-item>

          <!-- 多处登录 -->
          <el-form-item label="多处登录">
            <el-switch
              v-model="formData.multipoint_login"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>

          <el-form-item label="备注">
            <el-input v-model="formData.remark" type="textarea" />
          </el-form-item>
          <el-form-item label="审核权限">
            <el-switch
              v-model="formData.review"
              :active-value="1"
              :inactive-value="0"
              @change="onchange"
            />
          </el-form-item>
          <div
            v-if="formData.review == 1"
            class="bors"
            style="margin-bottom: 20px"
          >
            <div>入库单</div>
            <el-table
              :data="tableDatas"
              border
              style="width: 100%; margin-bottom: 10px"
              height="200"
              ref="multipleTableRef"
              @selection-change="onselect"
              :row-key="getAssign"
            >
              <el-table-column type="selection" width="30" align="center" />
              <el-table-column
                prop="title"
                label="入库仓库"
                width="160"
                show-overflow-tooltip
              />
              <el-table-column prop="checkList" label="物料分类">
                <template #default="scope">
                  <el-checkbox-group v-model="scope.row.selected">
                    <el-checkbox
                      v-for="(item, index) in scope.row.checkList"
                      :key="index"
                      :label="item.id"
                      >{{ item.name }}</el-checkbox
                    >
                  </el-checkbox-group>
                </template>
              </el-table-column>
            </el-table>

            <div>调拨单</div>
            <el-table
              :data="tableDatas2"
              border
              style="width: 100%; margin-bottom: 10px"
              height="200"
              ref="multipleTableRef2"
              @selection-change="onselect2"
            >
              <el-table-column type="selection" width="30" align="center" />
              <el-table-column
                prop="title"
                label="出库仓库"
                width="160"
                show-overflow-tooltip
              />
              <el-table-column prop="checkList" label="物料分类">
                <template #default="scope">
                  <el-checkbox-group v-model="scope.row.selected">
                    <el-checkbox
                      v-for="(item, index) in scope.row.checkList"
                      :key="index"
                      :label="item.id"
                      >{{ item.name }}</el-checkbox
                    >
                  </el-checkbox-group>
                </template>
              </el-table-column>
            </el-table>
            <div>作废单</div>
            <el-table
              :data="tableDatas3"
              border
              style="width: 100%; margin-bottom: 10px"
              height="200"
              ref="multipleTableRef3"
              @selection-change="onselect3"
            >
              <el-table-column type="selection" width="30" align="center" />
              <el-table-column
                prop="title"
                label="作废仓库"
                width="160"
                show-overflow-tooltip
              />
              <el-table-column prop="checkList" label="物料分类">
                <template #default="scope">
                  <el-checkbox-group v-model="scope.row.selected">
                    <el-checkbox
                      v-for="(item, index) in scope.row.checkList"
                      :key="index"
                      :label="item.id"
                      >{{ item.name }}</el-checkbox
                    >
                  </el-checkbox-group>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%"
          max-height="250"
          :row-class-name="rowClassName"
        >
          <el-table-column
            type="index"
            label="序号"
            align="center"
            width="55"
          />
          <el-table-column
            prop="date"
            align="left"
            label="绑定仓库"
            min-width="180"
          >
            <template #default="{ row }">
              <el-select
                class="flex-1"
                v-model="row.warehouse_id"
                size="small"
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, index) in options.listColumn"
                  :key="index"
                  :label="item.title"
                  :value="item.id"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            prop="name"
            align="left"
            label="仓库权限"
            min-width="180"
          >
            <template #default="{ row }">
              <el-select
                class="flex-1"
                v-model="row.permissions_id"
                size="small"
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, index) in options.all"
                  :key="index"
                  :label="item.title"
                  :value="item.id"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="55" align="center">
            <template #default="{ row }">
              <el-button
                link
                type="danger"
                size="small"
                @click="deleteRow(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button class="mt-4" style="width: 100%" @click="onAddItem"
          >添加</el-button
        >
        <!-- </el-form-item> -->
        <!-- <el-form-item label="财务权限">
                    <el-switch v-model="formData.review" :active-value="1" :inactive-value="0" @change="onchange" />
                </el-form-item> -->
        <el-table
          :data="tableData1"
          border
          stripe
          style="width: 100%"
          max-height="250"
          :row-class-name="rowClassName"
        >
          <el-table-column
            type="index"
            label="序号"
            align="center"
            width="55"
          />
          <!--
                    <el-table-column prop="date" align="left" label="项目名称" min-width="180">
                        <template #default="{ row }">
                            <el-select
                                class="flex-1"
                                v-model="row.project_id"
                                size="small"
                                placeholder="请选择"
                            >
                                <el-option
                                    v-for="(item, index) in projectList"
                                    :key="index"
                                    :label="item.title"
                                    :value="item.id"
                                ></el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                -->
          <el-table-column prop="name" align="left" label="权限名称">
            <template #default="{ row }">
              <el-select
                class="flex-1"
                style="width: 100%"
                v-model="row.permissions_id"
                size="small"
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, index) in limitsList"
                  :key="index"
                  :label="item.title"
                  :value="item.id.toString()"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="{ row }">
              <el-button
                link
                type="danger"
                size="small"
                @click="deleteRow1(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button class="mt-4" style="width: 100%" @click="onAddItem1"
          >添加</el-button
        >
      </el-form>
    </popup>
  </div>
</template>
<script lang="ts" setup>
import type { FormInstance } from "element-plus";
import Popup from "@/components/popup/index.vue";
import pickerold from "@/components/material/pickerold.vue";
import { roleLists, getReviewBase } from "@/api/perms/role";
import { adminAdd, adminEdit, adminPermissionsall } from "@/api/perms/admin";
import * as messageApi from "@/api/financial/message";
import * as limitsApi from "@/api/financial/limits";
import { deptLists } from "@/api/org/department";
import { jobsLists } from "@/api/org/post";
import { adminlistColumn } from "@/api/warehouse/list";

const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleTableRef2 = ref<InstanceType<typeof ElTable>>();
const multipleTableRef3 = ref<InstanceType<typeof ElTable>>();

const onselect = (val: User[]) => {
  multipleTableRef.value = val;
  formData.permission_config.type_10 = val;
};
const toggleSelection = (rows?: User[], ref: any) => {
  nextTick(() => {
    if (rows) {
      rows.forEach((row) => {
        setTimeout(() => {
          ref!.toggleRowSelection(row, true);
        }, 100);
      });
    } else {
      ref!.clearSelection();
    }
  });
};
const getAssign = () => {};
const onchange = (val: any) => {
  if (val == 1) {
    getOptions();
  }
};

const onselect2 = (val: User[]) => {
  multipleTableRef2.value = val;
  formData.permission_config.type_20 = val;
};
const onselect3 = (val: User[]) => {
  multipleTableRef3.value = val;
  formData.permission_config.type_30 = val;
};
const emit = defineEmits(["success", "close"]);
const formRef = shallowRef<FormInstance>();
const popupRef = shallowRef<InstanceType<typeof Popup>>();
const mode = ref("add");
const popupTitle = computed(() => {
  return mode.value == "edit" ? "编辑管理员" : "新增管理员";
});

const rowClassName = ({ row, rowIndex }) => {
  //把每一行的索引放进row
  row.index = rowIndex;
};
const formData = reactive({
  id: "",
  account: "",
  name: "",
  dept_id: "",
  jobs_id: "",
  role_id: "",
  avatar: "",
  password: "",
  password_confirm: "",
  disable: 0,
  multipoint_login: 1,
  root: 0,
  remark: "",
  bind_warehouse_id: "",
  warehouse_permissions: [],
  finance_account_permissions: [],
  review: 0,
  permission_config: {
    type_10: {},
    type_20: {},
    type_30: {},
  },
});

const formRules = reactive({
  account: [
    {
      required: true,
      message: "请输入账号",
      trigger: ["blur"],
    },
  ],
  name: [
    {
      required: true,
      message: "请输入名称",
      trigger: ["blur"],
    },
  ],
  role_id: [
    {
      required: true,
      message: "请选择角色",
      trigger: ["blur"],
    },
  ],
  bind_warehouse_id: [
    {
      required: true,
      message: "请选择仓库",
      trigger: ["blur"],
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: ["blur"],
    },
  ] as any[],
  password_confirm: [
    {
      required: true,
      message: "请输入确认密码",
      trigger: ["blur"],
    },
  ] as any[],
});
const options = reactive({
  role: [] as any[],
  dept: [] as any[],
  jobs: [] as any[],
  listColumn: [] as any[],
  all: [] as any[],
});
const tableData = ref([]);

const deleteRow = (val: any) => {
  tableData.value.splice(val.index, 1);
};
const deleteRow1 = (val: any) => {
  tableData1.value.splice(val.index, 1);
};
const onAddItem = () => {
  tableData.value.push({
    warehouse_id: "",
    permissions_id: "",
  });
};
const onAddItem1 = () => {
  tableData1.value.push({
    // project_id: '',
    permissions_id: "",
  });
};
watch(formData, (newValue) => {
  const arring = newValue.warehouse_permissions;
  if (arring.length != 0) {
    tableData.value = JSON.parse(arring);
  }
});

const tableDatas = ref([]);
const tableDatas1 = ref([]);
const tableDatas2 = ref([]);
const tableDatas3 = ref([]);
const removeRepeat = (arr: any) => {
  const result = [];
  const temp = {};
  arr.forEach((item) => {
    if (!temp[item.id]) {
      result.push(item);
      temp[item.id] = true;
    }
  });
  return result;
};
const getOptions = () => {
  adminPermissionsall({
    page_type: 0,
  }).then((data: any) => {
    options.all = data;
  });
  roleLists({
    page_type: 0,
  }).then((data: any) => {
    options.role = data.lists;
  });
  deptLists({
    page_type: 0,
  }).then((data: any) => {
    options.dept = data;
  });
  jobsLists({
    page_type: 0,
  }).then((data: any) => {
    options.jobs = data.lists;
  });
  adminlistColumn({
    page_type: 0,
  }).then((data: any) => {
    // console.log('2131', data)
    options.listColumn = data;
  });

  getReviewBase().then((data: any) => {
    for (const i of data.warehouse) {
      tableDatas.value.push({
        title: i.title,
        id: i.id,
        checkList: data.productCategory,
        selected: [],
      });
      tableDatas2.value.push({
        title: i.title,
        id: i.id,
        checkList: data.productCategory,
        selected: [],
      });
      tableDatas3.value.push({
        title: i.title,
        id: i.id,
        checkList: data.productCategory,
        selected: [],
      });
    }
    if (popupTitle.value == "新增管理员") {
    } else {
      if (formData.permission_config.type_10) {
        const arr10 = formData.permission_config.type_10.concat(
          tableDatas.value
        );
        tableDatas.value = removeRepeat(arr10);
        toggleSelection(
          formData.permission_config.type_10,
          multipleTableRef.value
        );
      }
      if (formData.permission_config.type_20) {
        const arr20 = formData.permission_config.type_20.concat(
          tableDatas2.value
        );
        tableDatas2.value = removeRepeat(arr20);
        toggleSelection(
          formData.permission_config.type_20,
          multipleTableRef2.value
        );
      }
      if (formData.permission_config.type_30) {
        const arr30 = formData.permission_config.type_30.concat(
          tableDatas3.value
        );
        tableDatas3.value = removeRepeat(arr30);
        toggleSelection(
          formData.permission_config.type_30,
          multipleTableRef3.value
        );
      }
    }
  });
};

const handleSubmit = async () => {
  await formRef.value?.validate();
  const arry = tableData.value;
  for (let i = arry.length - 1; i >= 0; i--) {
    if (arry[i].warehouse_id == "" || arry[i].permissions_id == "") {
      arry.splice(i, 1);
    }
  }
  const arry1 = tableData1.value;
  for (let i = arry1.length - 1; i >= 0; i--) {
    // if (arry1[i].project_id == '' || arry1[i].permissions_id == '') {
    if (arry1[i].permissions_id == "") {
      arry1.splice(i, 1);
    }
  }

  formData.warehouse_permissions = JSON.stringify(arry);
  formData.finance_account_permissions = arry1.map(
    (item) => item.permissions_id
  );

  mode.value == "edit" ? await adminEdit(formData) : await adminAdd(formData);
  popupRef.value?.close();
  emit("success");
};

const open = (type = "add") => {
  mode.value = type;
  popupRef.value?.open();
  getData();
};
const projectList = ref([]);
const limitsList = ref([]);
const tableData1 = ref([]);
const getData = async () => {
  const res = await limitsApi.adminListss({});
  limitsList.value = res.lists;
  const res1 = await messageApi.adminListss({});
  projectList.value = res1.lists;
};
const setFormData = (data: Record<any, any>) => {
  for (const key in formData) {
    if (data[key] != null && data[key] != undefined) {
      //@ts-ignore
      if (data.bind_warehouse_id) {
        for (let i = 0; i < data.bind_warehouse_id.length; i++) {
          data.bind_warehouse_id[i] = Number(data.bind_warehouse_id[i]);
        }
      }
      if (key === "finance_account_permissions") {
        tableData1.value = data[key].map((id) => ({ permissions_id: id }));
      }
      formData[key] = data[key];
    }
  }
  formRules.password = [];
  formRules.password_confirm = [];
};

const handleClose = () => {
  emit("close");
};

getOptions();

defineExpose({
  open,
  setFormData,
});
</script>
<style lang="scss" scoped>
.bors {
  border: 1px solid #dcdfe6;
  min-height: 100px;
  border-radius: 3px;
  padding: 5px;
}

// $bor-color:#eeeff0;
// .el-col {
// 	border-right: 1px solid $bor-color;
// 	border-top: 1px solid $bor-color;
// 	align-items: center;
// 	padding: 7px;

// 	&:nth-child(even) {
// 		border-right: 0;
// 	}
// }

// .el-form-item {
// 	margin-bottom: 0;
// }

// ::v-deep .el-form-item__label {
// 	border-left: 0;
// 	border-top: 0;
// 	border-bottom: 0;
// 	margin-right: 10px;
// }
// .bor {
// 	border: 1px solid $bor-color;
// 	margin-bottom: 20px;

// 	.bor-title {
// 		width: 100%;
// 		height: 40px;
// 		padding: 10px;
// 		background-color: #F8F8F8;
// 	}
// }

// ::v-deep .el-form-item__error {
// 	z-index: 10;
// }
</style>
